/*
Copyright 2010 Johan Maasing

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package nu.zoom.android.gdata.project.client.activity;

import nu.zoom.android.gdata.project.client.Paginator;
import nu.zoom.android.gdata.project.client.WKC;
import nu.zoom.android.gdata.project.integration.ProjectHostingClient.Feed;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;

/**
 * @author Johan Maasing
 * 
 */
public abstract class PaginatedListActivity<FeedType extends Feed<RowType>, RowType> extends
		FeedrunnerListActivity<FeedType, RowType> {
	protected Paginator paginator;
	private final int paginatorID;

	/**
	 * 
	 * @param layoutID
	 *            The view layout.
	 * @param paginatorID
	 *            The id of the paginator.
	 * @param rowlayoutID
	 *            The row layout.
	 */
	public PaginatedListActivity(final int layoutID, final int paginatorID) {
		super(layoutID);
		this.paginatorID = paginatorID;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		paginator = (Paginator) findViewById(paginatorID);
		paginator.setNextListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				final SharedPreferences sharedPreferences = getSharedPreferences(WKC.PREFERENCES_NAME, MODE_PRIVATE);
				String batchSizeString =
						sharedPreferences.getString(WKC.PREFERENCES.BATCH_KEY, WKC.BATCH_NUMBER_OF_ISSUES);
				startPosition += Integer.parseInt(batchSizeString);
				runFeedQuery();
			}
		});
		paginator.setPreviousListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				final SharedPreferences sharedPreferences = getSharedPreferences(WKC.PREFERENCES_NAME, MODE_PRIVATE);
				String batchSizeString =
						sharedPreferences.getString(WKC.PREFERENCES.BATCH_KEY, WKC.BATCH_NUMBER_OF_ISSUES);
				startPosition -= Integer.parseInt(batchSizeString);
				runFeedQuery();
			}
		});
	}


	@Override
	protected void issueResult(FeedType issueFeed) {
		super.issueResult(issueFeed);
		setPaginatorIndices() ;
	}

	protected void setPaginatorIndices() {
		paginator.setIndices(startPosition, (adapter.getCount() + startPosition) - 1, numEntries);
	}

}
